package com.tenglong.teacher.ui.setting.setting;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.cuotibao.zhuoxiao.basics.utils.recyview.DividerSpaceItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.MessageInfo;
import com.tenglong.teacher.data.resultInfo.VerifyMessageInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.MessageAdapter;
import com.tenglong.teacher.ui.common.activity.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class VerifyMessageActivity extends BaseActivity implements OnRefreshListener, MessageAdapter.MessageListener {

    public static final String KEY_VERIFY_MESSAGE_NUMBER = "key_verify_message_number";
    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mSmartRefreshLayout;
    private View noData;
    private List<MessageInfo> infos;
    private MessageAdapter mAdapter;
    private boolean isFirstDownLoad = true;
    private int unReadNum = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_message);
        initView();
        initRecy();
        setAdapte();
        setListeners();
        request();
    }

    private void initView() {
        setTitle("验证消息");
        mRecyclerView = findViewById(R.id.mRecyclerView);
        noData = findViewById(R.id.noData);
        mSmartRefreshLayout = findViewById(R.id.mSmartRefreshLayout);
        ClassicsHeader headerView = new ClassicsHeader(this);
        ClassicsFooter footView = new ClassicsFooter(this);
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        mSmartRefreshLayout.setRefreshHeader(headerView);
        mSmartRefreshLayout.setRefreshFooter(footView);
    }

    private void initRecy() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(new DividerSpaceItemDecoration(Utils.dip2px(this, 15)));
    }

    private void setAdapte() {
        infos = new ArrayList<>();
        mAdapter = new MessageAdapter(infos);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void setListeners() {
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
        mAdapter.setMessageListener(this);
    }

    private void request() {
        if (isFirstDownLoad) {
            isFirstDownLoad = false;
            showProgressDialog("数据加载中...");
        }
        CreateRequestEntity.getWebService().getVerifyMessageInfo().enqueue(new Callback<BaseResult<List<VerifyMessageInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<VerifyMessageInfo>>> call, Response<BaseResult<List<VerifyMessageInfo>>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    unReadNum = 0;
                    for (VerifyMessageInfo info : response.body().data) {
                        if (info.status == 0) {
                            unReadNum += 1;
                        }
                    }
                    infos.clear();
                    infos.addAll(response.body().data);
                    mAdapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                mSmartRefreshLayout.finishRefresh(true);
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<List<VerifyMessageInfo>>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                dismissProgressDialog();
                mSmartRefreshLayout.finishRefresh(false);
            }
        });
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        request();
    }

    @Override
    public synchronized void onInformListener(int position) {
        noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
        unReadNum -= 1;
    }

    @Override
    public void onVerifyMessageEvent(int position, boolean isAgree) {
        agreeOrReject(isAgree ? 1 : 2, position);
    }


    private void agreeOrReject(final int type, final int position) {
        if (infos == null || infos.size() <= position) return;
        MessageInfo info = infos.get(position);
        if (!(info instanceof VerifyMessageInfo)) return;
        final VerifyMessageInfo data = (VerifyMessageInfo) info;
        showProgressDialog("数据请求中...");
        CreateRequestEntity.getWebService().agreeOrRejectAddClass(data.id, type).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    data.status = type;
                    if (type == 1) {
                        if (infos != null && infos.size() > position) {
                            infos.remove(position);
                            mAdapter.notifyItemRemoved(position);
                            ToastUtils.showCenterToast("已同意");
                        }
                    } else {
                        mAdapter.notifyItemChanged(position);
                    }
                    noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                    unReadNum -= 1;
                    Intent intent = new Intent();
                    intent.putExtra(KEY_VERIFY_MESSAGE_NUMBER, unReadNum);
                    setResult(Activity.RESULT_OK, intent);
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
            }
        });
    }
}
